<template>
	<view class="content">
		<view v-if="upId==1">单个上传文件 - 示例</view>
		<button v-if="upId==1" type="primary" @click="uploadFail(1)">上传单个文件</button>
		<view v-if="upId==2">多个上传文件 - 示例</view>
		<button v-if="upId==2" type="primary" @click="uploadFail(2)">上传多个文件</button>
	</view>
</template>

<script>
	export default {
		props:{
			'id':{
				type:String
			}
		},
		data() {
			return {
				upId:1
			}
		},
		created() {

		},
		mounted() {
			console.log(this.id)
			this.upId=this.id;
		},
		methods: {
			uploadFail() {
				var that=this;
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						
						if(that.upId==2){//批量上传
							var tmp=[];
							let images=new Promise((resolve,reject)=>{
								for(var i=0;i<tempFilePaths.length;i++){
									uni.uploadFile({
										url: '/wx/imgUpload.jspx', //仅为示例，非真实的接口地址
										filePath: tempFilePaths[i],
										name: 'uploadFile',//此处为后台规定
										formData: {//此处为后台规定
											'wx': 'wx'
										},
										success: (uploadFileRes) => {
											tmp.push(uploadFileRes.data)
											
											if(tmp.length==tempFilePaths.length){
												resolve(tmp)
											}
										}
									});
								}
							})
							images.then(res=>{
								that.$emit('upload',res)
							})
							return
						}
						let uploadTask=uni.uploadFile({
							url: '/wx/imgUpload.jspx', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: 'uploadFile',//此处为后台规定
							formData: {//此处为后台规定
								'wx': 'wx'
							},
							success: (uploadFileRes) => {
								that.$emit('upload',uploadFileRes.data)
							}
						});
						uploadTask.onProgressUpdate((res) => {
							that.$emit('progress',res)
							console.log('上传进度' + res.progress);
							console.log('已经上传的数据长度' + res.totalBytesSent);
							console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
				
							// 测试条件，取消上传任务。
							// if (res.progress > 50) {
							// 	uploadTask.abort();
							// }
						});
					}
				});
			},
		}
	}
</script>

<style>
	.upload {
		width: 690rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 10rpx;
		border: 1rpx solid #ccc;
		text-align: center;
		margin-top: 50rpx;
	}
</style>
